# chat/consumers.py
# import json
# from channels.exceptions import *
import random

from channels.generic.websocket import AsyncJsonWebsocketConsumer
from chat.models import Room
from channels.db import database_sync_to_async

from record.models import Record
from user.models import User


class ChatConsumer(AsyncJsonWebsocketConsumer):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.user_id = None
        self.user = None
        self.room_id = None
        self.room = None
        self.room_name = None
        self.room_group_name = None

    async def connect(self):
        print(self.scope['url_route'])
        self.room_id = self.scope['url_route']['kwargs']['room_id']
        try:
            self.room = await database_sync_to_async(Room.objects.get)(id=self.room_id)
        except:
            return await self.close()
        self.room_name = self.room.room_name
        # print(self.room_name)
        self.user_id = self.scope['url_route']['kwargs']['user_id']
        if self.user_id != 'pc':
            self.user = await database_sync_to_async(User.objects.get)(id=self.user_id)
            # print(self.user.username)
        self.room_group_name = 'chat_%s' % self.room_name
        # Join room group
        await self.channel_layer.group_add(
            self.room_group_name,
            self.channel_name
        )
        await self.accept()

    async def disconnect(self, close_code):
        print('disconnect:', self.room_name)
        # Leave room group
        await self.channel_layer.group_discard(
            self.room_group_name,
            self.channel_name
        )
        # raise StopConsumer

    # Receive message from WebSocket
    async def receive_json(self, content, **kwargs):
        print(content)
        if content['type'] == 'chat':
            if not self.user:
                return
            data = content['data']
            words = data['words']
            imgs = data['imgs']

            # 聊天消息入库
            try:
                record = await database_sync_to_async(
                    Record.objects.create
                )(
                    content=words,
                    user=self.user,
                    room=self.room
                )
            except Exception as e:
                print(e)
                return
            # Send message to room group
            await self.channel_layer.group_send(
                self.room_group_name,
                {
                    'type': 'chat_message',
                    'message': {
                        'type': 'chat',
                        'data': {
                            'id': record.id,
                            'time': record.created_time.strftime('%Y-%m-%d %H:%M:%S'),
                            'nick': self.user.nickname,
                            'avatar': str(self.user.avatar),
                            'sex': random.randint(0, 2),
                            'words': record.content,
                            'imgs': [],
                        },
                    },
                }
            )
        elif content['type'] == '其他类型':
            pass

    # Receive message from room group
    async def chat_message(self, event):
        # Send message to WebSocket
        await self.send_json(event['message'])
